import express from "express";
import logger from "morgan";
import * as path from "path";
import { errorHandler, errorNotFoundHandler } from "./middleware/errorHandler";
import swaggerUi from 'swagger-ui-express';
import { swaggerDocs } from './utils/swagger';
import cors from 'cors';

// Routes
import indexRouter from './routes/index';
import usersRouter from './routes/users';
import smsRouter from './routes/sms';

// Create Express server
 const app = express();

// Express configuration
app.set("port", process.env.PORT || 4000);

// 设置跨域
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'book-token']
}));

// 设置超时时间
app.use((req, res, next) => {
  res.setTimeout(100000, () => {
    res.status(408).send('Request Timeout');
  });
  next();
});
app.set("views", path.join(__dirname, "../views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "../public")));
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/sms', smsRouter);

app.use(errorNotFoundHandler);
app.use(errorHandler);
export default app;
